﻿using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using Quartz.NET.Web.Constant;
using Quartz.NET.Web.Enum;
using Quartz.NET.Web.Extensions;
using Quartz.NET.Web.Models;
using Serilog;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace Quartz.NET.Web.Utility
{
    public class FileQuartz
    {
        private static string _rootPath { get; set; }

        private static string _logPath { get; set; }

       private static IFreeSql freeSql => HttpContext.Current.RequestServices.GetService<IFreeSql>();

        /// <summary>
        /// 创建作业所在根目录及日志文件夹 
        /// </summary>
        /// <returns></returns>
        public static string CreateQuartzRootPath(IWebHostEnvironment env)
        {
            if (!string.IsNullOrEmpty(_rootPath))
                return _rootPath;
            _rootPath = $"{Directory.GetParent(env.ContentRootPath).FullName}\\{QuartzFileInfo.QuartzSettingsFolder}\\";
            _rootPath = _rootPath.ReplacePath();
            if (!Directory.Exists(_rootPath))
            {
                Directory.CreateDirectory(_rootPath);
            }
            _logPath = _rootPath + QuartzFileInfo.Logs + "\\";
            _logPath = _logPath.ReplacePath();
            //生成日志文件夹
            if (!Directory.Exists(_logPath))
            {
                Directory.CreateDirectory(_logPath);
            }
            return _rootPath;
        }

        /// <summary>
        /// 初始化作业日志文件,以txt作为文件
        /// </summary>
        /// <param name="groupJobName"></param>
        public static void InitGroupJobFileLog(string groupJobName)
        {
            string jobFile = _logPath + groupJobName;
            jobFile = jobFile.ReplacePath();
            if (!File.Exists(jobFile))
            {
                File.Create(jobFile);
            }
        }

        /// <summary>
        /// 查询任务日志
        /// </summary>
        /// <param name="taskId"></param>
        /// <param name="page"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public static List<TaskLog> GetJobRunLog(string taskId, int page, int pageSize = 30)
        {
           // string path = $"{_logPath}{groupName}\\{taskName}.txt";
            List<TaskLog> list = new List<TaskLog>();

 
             list=freeSql.Select<TaskLog>().Where(x=>x.taskId==taskId)
           .OrderByDescending(x=>x.BeginDate)
             .Page(page,pageSize).ToList();

            return list;
        }

        /// <summary>
        /// 查询任务日志
        /// </summary>
        /// <param name="taskId"></param>
        /// <param name="page"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public static TableResult<TaskLog> GetJobLogByPage(string taskId, int offset, int limit = 30,string search="")
        {
            TableResult<TaskLog> res = new TableResult<TaskLog>();
            long total = 0;
            List<TaskLog> list = new List<TaskLog>();

            list = freeSql.Select<TaskLog>()
             
            .WhereIf(!string.IsNullOrWhiteSpace(search),a=>a.Msg.Contains(search))
             .WhereIf(!string.IsNullOrWhiteSpace(taskId), x => x.taskId == taskId)
              .OrderByDescending(x => x.BeginDate)
              .Offset(offset)
          .Limit(limit)
            //.Page(page, pageSize)
            .Count(out total)
            .ToList();
            res.total = total;
            res.rows = list;
            return res;
        }



        public static void WriteJobAction(JobAction jobAction, string taskName, string groupName, string content = null)
        {
            content = $"{jobAction.ToString()} --  {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}  --分组：{groupName},作业：{taskName},消息:{content ?? "OK"}\r\n";
            Log.Information(content);
        }

 
        public static string GetAccessLog(int pageSize=1)
        {
            string path = FileQuartz.LogPath + "access.txt";
            path = path.ReplacePath();
            if (!File.Exists(path))
                return "没有找到目录";
            return string.Join("<br/>", FileHelper.ReadPageLine(path, pageSize, 5000, true).ToList());
        }
        public static string RootPath
        {
            get { return _rootPath; }
        }

        public static string LogPath
        {
            get { return _logPath; }
        }
    }
}
